var express = require('express');
var router = express.Router();
var request = require('request');
var accessToken = "5_lNdDzwxBvzG6qLs1xw0QgQGstf0ZylHJzcUvmVx3L6CFjqEd-Wz_qSnOc1UpDYzmOowuYCzFQuHf7FzkOEBto49xdE3PUGSY6SqjntIKS5dARBU6AshMEsvtkW0sImasZ7XhLdyyBtpUAbvXDZLbAGANJV";
var accessTokenApi = require('../token/accessToken');
var wxConfig = require('../config/config');
var db = require('../../db/mysql/pool');

router.post('/jkyx/send-message',async function(req,res,next){

    //let token = await accessTokenApi.getAccessToken();console.log(token);
    let result = await getFansOpenid(accessToken);
    let openids = result.data.openid;
    //let openids = ['oMRuEwTPg-I02St5vAD1Tsf6rgf4'];
    //let resk = await sendMessage('oMRuEwTPg-I02St5vAD1Tsf6rgf4');res.end(JSON.stringify(resk));
    openids.forEach(openid => {
        sendMessage(openid);
    });
    
});

function sendMessage(openid)
{
    var postParam = {
        "touser":openid,
        "template_id":"61zEK4NlozcVrpHo2ye2Gkf7lZPhQQDAy_25MT7VLJ8",
        "url":"http://sc.jackfresh.cn",
        "data":{
            "first":{
                "value":"测试一条",
                "color":"#173177"
            },
            "keyword1":{
                "value":"测试1",
                "color":"#173177"
            },
            "keyword2":{
                "value":"测试2",
                "color":"#173177"
            },
            "keyword3":{
                "value":"测试3",
                "color":"#173177"
            },
            "remark":{
                "value":"测试备注",
                "color":"#173177"
            }
        }
    };
    var postData = {
        url:wxConfig.templateMessageUrl+accessToken,
        form:JSON.stringify(postParam)
    };    
    request.post(postData,function(err,response,result){
        if(err)
        {
            console.log("发送失败:"+err);
        }
    });

}

function getFansOpenid(token)
{
    return new Promise(function(resolve, reject){
        request.get(wxConfig.getFansOpenid+token,function(err, response, body){
            if(err)
            {
                return reject(err);
            }
            resolve(response);
        });
    });
}

module.exports = router;
